const { request } = require('../../../utils/request');
const pageBehavior = require('../../../utils/pageBehavior');
const { navigateTo } = require('../../../utils/navigation');

Page({
  behaviors: [pageBehavior],

  data: {
    status: '',
    reason: '',
    canSubmit: false
  },

  onShow() {
    this.fetchStatus();
  },

  async fetchStatus() {
    await this.executeAsync(
      async () => {
        const res = await request({
          url: '/api/miniapp/profile/status',
          method: 'GET',
          showErrorToast: false
        });
        const data = res?.data || {};
        const status = data.status || 'DRAFT';
        this.setData({
          status,
          reason: data.reason || data.remark || '',
          canSubmit: status === 'DRAFT' || status === 'REJECTED'
        });
      },
      {
        showLoading: true,
        showError: true,
        defaultMessage: '加载状态失败'
      }
    );
  },

  async submitReview() {
    if (!this.data.canSubmit || this.data.loading) {
      return;
    }

    await this.executeAsync(
      async () => {
        await request({ url: '/api/miniapp/profile/submit', method: 'POST' });
        this.showSuccess('已提交审核');
        this.fetchStatus();
      },
      {
        showLoading: true,
        showError: true
      }
    );
  },

  goProfile() {
    navigateTo('/pages/profile/profile', {}, 'redirectTo');
  }
});
